﻿using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace CRL.MySql
{
    partial class MySqlHelper
    {
        public override async Task InsertFromDataTableAsync(DataTable dataTable, string tableName, bool keepIdentity = false)
        {
            //批量写入问题
            //https://blog.csdn.net/weixin_35440082/article/details/113424636

            //异步方法报错
            //MySqlBulkCopy sqlBulkCopy;
            //if (_trans != null)
            //{
            //    var sqlTrans = _trans as MySqlTransaction;
            //    sqlBulkCopy = new MySqlBulkCopy(currentConn as MySqlConnection, sqlTrans);
            //}
            //else
            //{
            //    GetOrCreateConn();
            //    sqlBulkCopy = new MySqlBulkCopy(currentConn as MySqlConnection, null);
            //}
            //sqlBulkCopy.DestinationTableName = tableName;
            ////sqlBulkCopy.BatchSize = dataTable.Rows.Count;
            //if (dataTable != null && dataTable.Rows.Count != 0)
            //{
            //    await sqlBulkCopy.WriteToServerAsync(dataTable);
            //}

            if (dataTable.Rows.Count == 0) return;
            string tmpPath = Path.GetTempFileName();
            string csv = DataTableToCsv(dataTable);
            File.WriteAllText(tmpPath, csv);
            using (var conn = currentConn ?? CreateConn())
            {
                try
                {
                    MySqlBulkLoader bulk = new MySqlBulkLoader(conn as MySqlConnection)
                    {
                        FieldTerminator = ",",
                        FieldQuotationCharacter = '"',
                        EscapeCharacter = '"',
                        LineTerminator = "\r\n",
                        FileName = tmpPath,
                        NumberOfLinesToSkip = 0,
                        TableName = tableName,
                        Local = true,
                    };
                    //bulk.Columns.AddRange(table.Columns.Cast<DataColumn>().Select(colum => colum.ColumnName).ToArray());
                    var insertCount = await bulk.LoadAsync();
                }
                catch (MySqlException ex)
                {
                    throw ex;
                }
            }
            File.Delete(tmpPath);
        }
    }
}
